import * as SecureStore from 'expo-secure-store';

export type HistoryEntry = { id: number; title: string; viewedAt: string };

const KEY = 'view_history_v1';

async function read(): Promise<HistoryEntry[]> {
  try {
    const v = await SecureStore.getItemAsync(KEY);
    if (!v) return [];
    const arr = JSON.parse(v);
    if (!Array.isArray(arr)) return [];
    return arr.filter((e) => e && typeof e.id === 'number' && typeof e.title === 'string' && typeof e.viewedAt === 'string');
  } catch {
    return [];
  }
}

async function write(entries: HistoryEntry[]) {
  try {
    await SecureStore.setItemAsync(KEY, JSON.stringify(entries.slice(0, 100)));
  } catch {}
}

export async function addHistory(payload: { id: number; title: string }) {
  const now = new Date().toISOString();
  const prev = await read();
  const filtered = prev.filter((e) => e.id !== payload.id);
  const next: HistoryEntry[] = [{ id: payload.id, title: payload.title, viewedAt: now }, ...filtered];
  await write(next);
}

export async function getHistory(): Promise<HistoryEntry[]> {
  return read();
}

